//
//  MahjongControlView.m
//  Mahjong
//
//  Created by 饶首建 on 17/6/30.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MahjongControlView.h"
#import "MahjongAttributeCVC.h"
#import "MahjongControlPlayerView.h"
#import "MahjongAlertConfirmView.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import "HWPopTool.h"
#import "UIImage+Filter.h"

@interface MahjongControlView()<UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate>
@property (nonatomic,strong) UIWindow *window;

@end

static NSString *kMahjongAttributeCVC = @"kMahjongAttributeCVC";

@implementation MahjongControlView

- (void)sendAction{
    if (_selectedPlayerArr.count == 0) {
        [Hud hudText:@"请选择玩家" inView:self];
        return;
    }
    NSString *url = NSStringFormat(@"%@/Games/%@/actions",BASE_URL,_gameModel.gameId);
    NSMutableArray *tmp = [NSMutableArray new];
    for (PlayerModel *pm in _selectedPlayerArr) {
        [tmp addObject:@{
                         @"id":pm.playerId,
                         @"name":pm.playerName
                         }];
    }
    
    NSDictionary *param = @{
                            @"type":_controlType == ControlTypeGang?@"杠":(_controlType == ControlTypeHu?@"胡":@"查叫"),
                            @"attributes":_selectedAttributeArr,
                            @"owner":@{
                                    @"id":_owner.playerId,
                                    @"name":_owner.playerName
                                    },
                            @"targets":tmp
                            };
    if (_isEditAction) {
        [ActionModel putActionByGameId:_gameModel.gameId actionId:_actionModel.actionId param:param success:^(id model) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self];
        }];
    }else{
        [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self];
        }];
    }
}

- (IBAction)sureAction:(id)sender {
    [self sendAction];
}

//删除
- (IBAction)closeAction:(id)sender {
    if (_isEditAction) {
        [ActionModel deleteActionByGameId:_gameModel.gameId actionId:_actionModel.actionId success:^(id model) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self];
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        }];
    }else{
        [[HWPopTool sharedInstance] closeWithBlcok:^{}];
    }
}

+(instancetype)mahjongControlView{
    return [[[NSBundle mainBundle] loadNibNamed:@"MahjongControlView"
                                          owner:nil options:nil]lastObject];
}

- (void)setDataArr:(NSArray *)dataArr{
    _dataArr = dataArr;
    
    _titleLabel.text = _controlType == ControlTypeGang?@"杠":(_controlType == ControlTypeHu?@"胡":@"查叫");
    
    if (_isEditAction) {
        [_closeBtn setTitle:@"删除" forState:UIControlStateNormal];
        _closeIconBtn.hidden = NO;
        [_sureBtn setTitle:@"修改" forState:UIControlStateNormal];
    }else{
        [_closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
        _closeIconBtn.hidden = YES;
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    }
    
    if (!_selectedAttributeArr) {
        _selectedAttributeArr = [NSMutableArray new];
    }
    if (!_selectedPlayerArr) {
        _selectedPlayerArr = [NSMutableArray new];
    }
    [_collectionView reloadData];
    
    [self setPlayersView];
    
    NSString *mid = [[NSUserDefaults standardUserDefaults]stringForKey:@"MATCH_ID"];
    if (_controlType == ControlTypeHu && ![mid isEqualToString:_matchModel.matchId]) {
        [self alertAction];
    }
}

- (void)setPlayersView{
    for (UIView *v in _playerContainer.subviews) {
        [v removeFromSuperview];
    }
    
    //已胡玩家
    NSMutableArray *gonePlayerIdArr = [NSMutableArray new];
    for (ActionModel *am in _gameModel.actionArr) {
        if ([am.actionType isEqualToString:@"胡"]) {
            [gonePlayerIdArr addObject:am.owner.playerId];
        }
    }
    
    NSMutableArray *selectedPlayerIdArr = [NSMutableArray new];
    for (PlayerModel *p in _selectedPlayerArr) {
        [selectedPlayerIdArr addObject:p.playerId];
    }
    
    float w = _playerContainer.frame.size.width;
    for (int i = 0; i<_playersArr.count; i++) {
        MahjongControlPlayerView *pv = [MahjongControlPlayerView mahjongControlPlayerView];
        float pvW = pv.frame.size.width;
        float pvH = pv.frame.size.height;
        float margin = (w - pv.frame.size.width * _playersArr.count)/(_playersArr.count + 1);
        pv.frame = CGRectMake(margin*(i+1) + pvW * i, 0, pvW, pvH);
        [_playerContainer addSubview:pv];
        
        PlayerModel *pm = _playersArr[i];
        //昵称
        pv.nameLabel.text = pm.playerName;
        //头像
        if (pm.avatar.length) {
            [pv.avatarImageView sd_setImageWithURL:[NSURL URLWithString:pm.avatar] placeholderImage:UIImageWithName(@"default_head")];
            pv.firstNameLabel.text = @"";
        }else{
            pv.firstNameLabel.text = [pm.playerName substringToIndex:1];
        }
        //胡状态
        if ([gonePlayerIdArr containsObject:pm.playerId]) {
            pv.huImageView.hidden = NO;
        }else{
            pv.huImageView.hidden = YES;
        }
        //选中状态
        pv.selectedImageView.hidden = YES;
        pv.nameLabel.textColor = UIColorHex(9B9B9B);
        if ([selectedPlayerIdArr containsObject:pm.playerId]) {
            pv.selectedImageView.hidden = NO;
            pv.nameLabel.textColor = UIColorHex(F15A5A);
        }
        //是否可选
        if ([_matchModel.rules containsObject:@"血流成河"]) {
            pv.userInteractionEnabled = YES;
        }else{
            if ([gonePlayerIdArr containsObject:pm.playerId]) {
                pv.userInteractionEnabled = NO;
                pv.avatarImageView.image = [pv.avatarImageView.image grayImage];
            }else{
                pv.userInteractionEnabled = YES;
            }
        }
        
        __weak typeof(pv) weakPv = pv;
        pv.playerTapBlock = ^(id name){
            if ([_selectedAttributeArr containsObject:@"直杠"]) {
                for (MahjongControlPlayerView *pvv in _playerContainer.subviews) {
                    pvv.selectedImageView.hidden = YES;
                    pvv.nameLabel.textColor = UIColorHex(9B9B9B);
                }
                [selectedPlayerIdArr removeAllObjects];
                weakPv.selectedImageView.hidden = NO;
                weakPv.nameLabel.textColor = UIColorHex(F15A5A);
                [selectedPlayerIdArr addObject:pm.playerId];
            }else{
                if ([selectedPlayerIdArr containsObject:pm.playerId]) {
                    weakPv.selectedImageView.hidden = YES;
                    weakPv.nameLabel.textColor = UIColorHex(9B9B9B);
                    [selectedPlayerIdArr removeObject:pm.playerId];
                }else{
                    weakPv.selectedImageView.hidden = NO;
                    weakPv.nameLabel.textColor = UIColorHex(F15A5A);
                    [selectedPlayerIdArr addObject:pm.playerId];
                }
            }
            [_selectedPlayerArr removeAllObjects];
            for (PlayerModel *p in _playersArr) {
                if ([selectedPlayerIdArr containsObject:p.playerId]) {
                    [_selectedPlayerArr addObject:p];
                }
            }
        };
    }
}

- (void)alertAction{
    MahjongAlertConfirmView *mv = [MahjongAlertConfirmView mahjongAlertConfirmView];
    mv.alertTextLabel.text = @"已经为您计算了杠出来的牌,\n请不用再勾选【带根】牌型";
    UIViewController *vc = [[UIViewController alloc]init];
    vc.view.backgroundColor = UIColorFromRGBA(0x000000, 0.5);
    [vc.view addSubview:mv];
    mv.center = vc.view.center;
    _window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel = UIWindowLevelAlert + 10000;
    _window.opaque = NO;
    _window.rootViewController = vc;
    [_window makeKeyAndVisible];
    mv.neverAlertClickBlock = ^(){
        [_window removeFromSuperview];
        _window = nil;
        [[NSUserDefaults standardUserDefaults]setValue:_matchModel.matchId forKey:@"MATCH_ID"];
    };
    mv.knowClickBlock = ^(){
        [_window removeFromSuperview];
        _window = nil;
    };
    
    //    [UIAlertView showWithTitle:@"提示" message:@"已经杠出来的牌，不用再勾选牌型" cancelButtonTitle:@"知道了" otherButtonTitles:@[@"不再提醒"] tapBlock:^(UIAlertView * _Nonnull alertView, NSInteger buttonIndex) {
    //
    //    }];
}

- (void)awakeFromNib{
    [super awakeFromNib];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        [[HWPopTool sharedInstance]closeWithBlcok:^{}];
    }];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[MahjongAttributeCVC class] forCellWithReuseIdentifier:kMahjongAttributeCVC];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (_controlType == ControlTypeGang) {
        return 3;
    }
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MahjongAttributeCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kMahjongAttributeCVC forIndexPath:indexPath];
    NSString *attr = _dataArr[indexPath.row];
    [self stateForCell:cell selected:[_selectedAttributeArr containsObject:attr]];
    cell.titleLabel.text = attr;
    return cell;
}
#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    NSString *attr = _dataArr[indexPath.row];
    MahjongAttributeCVC *cell = (MahjongAttributeCVC*)[collectionView cellForItemAtIndexPath:indexPath];
    if (_controlType == ControlTypeGang) {
        [_selectedAttributeArr removeAllObjects];
        [_selectedAttributeArr addObject:attr];
        [collectionView reloadData];
    }else{
        if ([_selectedAttributeArr containsObject:attr]) {
            [self stateForCell:cell selected:NO];
            [_selectedAttributeArr removeObject:attr];
        }else{
            [self stateForCell:cell selected:YES];
            [_selectedAttributeArr addObject:attr];
        }
    }
    
    //player 选中状态
    if ([_selectedAttributeArr containsObject:@"补杠"]||[_selectedAttributeArr containsObject:@"暗杠"]||[_selectedAttributeArr containsObject:@"自摸"]||[_selectedAttributeArr containsObject:@"杠上花"]) {
        [_selectedPlayerArr removeAllObjects];
        for (PlayerModel *pm in [self leftPlayers]) {
            [_selectedPlayerArr addObject:pm];
        }
    }else{
        if (!_isEditAction) {
            [_selectedPlayerArr removeAllObjects];
        }
    }
    
    [self setPlayersView];
    
}

- (NSArray*)leftPlayers{
    if ([_matchModel.rules containsObject:@"血流成河"]) {
        return _matchModel.others;
    }else{
        //已胡玩家
        NSMutableArray *gonePlayerIdArr = [NSMutableArray new];
        for (ActionModel *am in _gameModel.actionArr) {
            if ([am.actionType isEqualToString:@"胡"]) {
                [gonePlayerIdArr addObject:am.owner.playerId];
            }
        }
        //未胡玩家
        NSMutableArray *leftPlayerArr = [NSMutableArray new];
        for (PlayerModel *pm in _matchModel.others) {
            if (![gonePlayerIdArr containsObject:pm.playerId]) {
                [leftPlayerArr addObject:pm];
            }
        }
        return leftPlayerArr;
    }
}

- (void)stateForCell:(MahjongAttributeCVC*)cell selected:(BOOL)flag{
    cell.layer.borderColor = flag?UIColorHex(F15A5A).CGColor:UIColorHex(9B9B9B).CGColor;
    cell.backgroundColor = flag?UIColorFromRGBA(0xF15A5A,0.1):[UIColor whiteColor];
    cell.titleLabel.textColor = flag?UIColorHex(F15A5A):UIColorHex(9B9B9B);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_controlType == ControlTypeGang) {
        return CGSizeMake(220, 100);
    }
    return CGSizeMake(150,74);
}
//section的内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//section之间的行距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 30;
}
//item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 12;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    // 取消响应手势
    if (touch.view == self){
        return YES;
    }
    return NO;
}

- (IBAction)closeBtnAction:(id)sender {
    [[HWPopTool sharedInstance] closeWithBlcok:^{}];
}

@end
